package com.xnf.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.xnf.admin.feign.ArticleFeign;
import com.xnf.admin.feign.WemediaFeign;
import com.xnf.admin.mapper.AdChannelMapper;
import com.xnf.admin.mapper.AdSensitiveMapper;
import com.xnf.admin.service.WemediaNewsAutoScanService;
import com.xnf.common.aliyun.GreeTextScan;
import com.xnf.common.aliyun.GreenImageScan;
import com.xnf.common.constants.wemeida.WemediaContans;
import com.xnf.common.fastdfs.FastDFSClientUtil;
import com.xnf.model.admin.dtos.NewsAuthDto;
import com.xnf.model.admin.pojos.AdChannel;
import com.xnf.model.article.pojos.ApArticle;
import com.xnf.model.article.pojos.ApArticleConfig;
import com.xnf.model.article.pojos.ApArticleContent;
import com.xnf.model.article.pojos.ApAuthor;
import com.xnf.model.common.dtos.PageResponseResult;
import com.xnf.model.common.dtos.ResponseResult;
import com.xnf.model.common.enums.AppHttpCodeEnum;
import com.xnf.model.wemeida.pojos.WmNews;
import com.xnf.model.wemeida.pojos.WmUser;
import com.xnf.model.wemeida.vo.WmNewsVo;
import com.xnf.utils.common.SensitiveWordUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.rest.RestStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 * Created by xnf on 2022/3/4.
 */

@Service
@Log4j2
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private GreeTextScan greeTextScan;
    @Value("${fdfs.url}")
    private String serverFilePath;
    @Autowired
    private FastDFSClientUtil fastDFSClient;
    @Autowired
    private AdSensitiveMapper sensitiveMapper;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private AdChannelMapper adChannelMapper;
    @Autowired
    private RestHighLevelClient client;
    @Override
    public void autoScanByMediaNewsId(Integer id) {
        if (id == null) {
            log.error("当前的审核id空");
            return;
        }
        WmNews wmNews = wemediaFeign.findById(id);
        if (wmNews == null) {
            log.error("审核的自媒体文章不存在，自媒体的id:{}", id);
            return;
        }
        //2.文章状态为4（人工审核通过）直接保存数据和创建索引
        if (wmNews.getStatus() == 4) {
            //保存数据
            saveAppArticle(wmNews,wmNews.getStatus());
            return;
        }
        //3文章状态为8 审核通过
        if (wmNews.getStatus() == 8 && wmNews.getPublishTime().getTime() < System.currentTimeMillis()) {
            //保存数据
            saveAppArticle(wmNews,wmNews.getStatus());
            return;
        }
        //4文章状态为1 待审核
        if (wmNews.getStatus() == 1) {
            Map<String, Object> contentAndImagesResult = handleTextAndImages(wmNews);
            System.out.println("contentAndImagesResult ====== "+ contentAndImagesResult);
            //4.1 文本审核
            String content = (String) contentAndImagesResult.get("content");
            boolean handleTextScan = handleTextScan(wmNews, content);
            if (!handleTextScan) return;
            //4.2 图片审核
            List<String> imageUrlList = (List<String>) contentAndImagesResult.get("images");
            System.out.println("imageUrlList ====== "+ imageUrlList);
            boolean handleImagesScan = handleImagesScan(wmNews, imageUrlList);
            if (!handleImagesScan) return;
            //4.3 自管理的敏感词审核
            boolean handleSensitive = handleSensitive(wmNews, content);
            if (!handleSensitive) return;
            //4.4 发布时间大于当前时间
            if (wmNews.getPublishTime().getTime() > System.currentTimeMillis()){
                //修改文章状态为8
                updateWmNews(wmNews, (short) 8, "审核通过，待发布");
                return;
            }
        }
        //5.审核通过，修改自媒体文章状态为9  保存app端相关文章信息
        saveAppArticle(wmNews, (short) 9);
    }

    private void saveAppArticle(WmNews wmNews,short status) {
        ApArticle apArticle = saveArticle(wmNews);
        System.out.println("保存文章成功");
        saveArticleConfig(apArticle);
        System.out.println("保存app文章配置成功");
        //保存app文章内容
        saveArticleContent(apArticle, wmNews);
        System.out.println("保存app文章内容成功");
        //修改自媒体文章的状态为9
        System.out.println(apArticle.getId());
        wmNews.setArticleId(apArticle.getId());
        updateWmNews(wmNews, status ,"审核通过，保存app端相关文章信息");
        System.out.println("审核通过，保存app端相关文章信息");
        //TODO es索引创建

        Map<String,Object> map = new HashMap();
        map.put("id",apArticle.getId().toString());
        map.put("publishTime",apArticle.getPublishTime());
        map.put("layout",apArticle.getLayout());
        map.put("images",apArticle.getImages());
        map.put("authorId",apArticle.getAuthorId());
        map.put("title",apArticle.getTitle());
        map.put("content",wmNews.getContent());
        IndexRequest indexRequest = new IndexRequest("app_info_article").id(apArticle.getId().toString()).source(map);

        try {
            IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);
            RestStatus restStatus = index.status();
            System.out.println(restStatus);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存文章内容
     * @param apArticle
     * @param wmNews
     */
    private void saveArticleContent(ApArticle apArticle, WmNews wmNews) {
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        articleFeign.saveArticleContent(apArticleContent);
    }

    /**
     * 创建app端文章配置信息
     *
     * @param apArticle
     */
    private void saveArticleConfig(ApArticle apArticle) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(true);
        apArticleConfig.setIsComment(true);
        articleFeign.saveArticleConfig(apArticleConfig);
    }

    /**
     * 保存文章
     *
     * @param wmNews
     * @return
     */
    private ApArticle saveArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setLayout(wmNews.getType());
        apArticle.setImages(wmNews.getImages());
        apArticle.setCreatedTime(new Date());
        //获取作者相关信息
        Integer wmUserId = wmNews.getUserId();
        WmUser wmUser = wemediaFeign.findWmUserById(wmUserId.longValue());
        if(wmUser != null){
            ApAuthor apAuthor = articleFeign.selectAuthorByName(wmUser.getName());
            if (apAuthor != null){
                apArticle.setAuthorId(apAuthor.getId().longValue());
                apArticle.setAuthorName(apAuthor.getName());
            }
        }
        Integer channelId = wmNews.getChannelId();
        AdChannel adChannel = adChannelMapper.selectById(channelId);
        if(adChannel != null){
            apArticle.setChannelId(channelId);
            apArticle.setChannelName(adChannel.getName());
        }
        apArticle.setLikes(0);
        apArticle.setCollection(0);
        apArticle.setComment(0);
        apArticle.setViews(0);
        apArticle.setPublishTime(wmNews.getPublishTime());
        return articleFeign.saveArticle(apArticle);
    }

    private boolean handleSensitive(WmNews wmNews, String content) {
        boolean flag = true;
        List<String> allSensitive = sensitiveMapper.findAllSensitive();
        SensitiveWordUtil.initMap(allSensitive);
        Map<String, Integer> resultMap = SensitiveWordUtil.matchWords(content);
        if (resultMap != null && resultMap.size() > 0){
            log.error("敏感词过滤没有通过，包含了敏感词:{}", resultMap);
            //找到了敏感词，审核不通过
            updateWmNews(wmNews, (short) 2,"文章中包含了敏感词");
            flag = false;
        }
        return flag;
    }


    /**
     * 审核图片
     *
     * @param imageUrlList
     * @param wmNews
     * @return
     */
    private boolean handleImagesScan(WmNews wmNews, List<String> imageUrlList) {
        boolean flag = true;
        List<byte[]> imageByteList = new ArrayList<>();
        try {
            for (String imageUrl : imageUrlList) {
                imageUrl = imageUrl.replace(serverFilePath, "");
                int indexOf = imageUrl.indexOf("/");
                System.out.println(imageUrl +"  " + "index "+indexOf);
                String group = imageUrl.substring(0, indexOf);
                String filePath = imageUrl.substring(indexOf + 1);
                byte[] bytes = fastDFSClient.download(group, filePath);
                imageByteList.add(bytes);
            }
            Map map = greenImageScan.imageScan(imageByteList);
            //审核不通过
            if (!map.get("suggestion").equals("pass")) {
                //审核失败
                if (map.get("suggestion").equals("block")) {
                    //修改自媒体文章的状态，并告知审核失败原因
                    updateWmNews(wmNews, (short) 2, "文章中图片有违规");
                    flag = false;
                }
                //人工审核
                if (map.get("suggestion").equals("review")) {
                    //修改自媒体文章的状态，并告知审核失败原因
                    updateWmNews(wmNews, (short) 3, "文章图片有不确定元素");
                    flag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /**
     * 修改自媒体文章
     *
     * @param wmNews
     * @param status
     * @param msg
     */
    private void updateWmNews(WmNews wmNews, short status, String msg) {
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        wemediaFeign.updateWmNews(wmNews);
    }

    /**
     * 审核文本
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(WmNews wmNews, String content) {
        boolean flag = true;
        try {
            Map map = greeTextScan.greeTextScan(content);
            //审核不通过
            if (map != null && !map.get("suggestion").equals("pass")) {
                //审核失败
                if (map.get("suggestion").equals("block")) {
                    updateWmNews(wmNews, (short) 2, "文章内容中有敏感词汇");
                    flag = false;
                }
                if (map.get("suggestion").equals("review")) {
                    updateWmNews(wmNews, (short) 3, "文章内容中有不确定词汇");
                    flag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /**
     * 提取文本内容和图片
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        String content = wmNews.getContent();
        if (StringUtils.isEmpty(content)) {
            log.error("审核的自媒体文章不存在内容，自媒体的id:{}" + wmNews.getId());
        }
        List<Map> maps = JSON.parseArray(content, Map.class);
        List<String> images = new ArrayList<>();
        StringBuffer sb = new StringBuffer();
        for (Map map : maps) {
            if (map.get("type").equals(WemediaContans.WM_NEWS_TYPE_IMAGE)) {
                String imgUrl = (String) map.get("value");
                images.add(imgUrl);
            } else {
                String value = (String) map.get("value");
                sb.append(value);
            }
        }

        if (wmNews.getType() != 0 && wmNews.getImages() != null) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", sb.toString());
        resultMap.put("images", images);
        return resultMap;
    }

    @Override
    public PageResponseResult findNews(NewsAuthDto dto) {

        PageResponseResult result = wemediaFeign.findList(dto);
        result.setHost(serverFilePath);
        return result;
    }

    @Override
    public ResponseResult findOne(Integer id) {
        //1参数检查
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNewsVo wmNewsVo = wemediaFeign.findWmNewsVo(id);
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(serverFilePath);
        return responseResult;
    }

    @Override
    public ResponseResult updateStatus(Integer type, NewsAuthDto dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = wemediaFeign.findById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (type == 0){
            System.out.println("审核没有通过");
            updateWmNews(wmNews, (short) 2,dto.getMsg());
        }else if(type == 1){
            //4.人工审核通过
            System.out.println("审核通过");
            if (wmNews.getPublishTime().getTime() > System.currentTimeMillis()){
                saveAppArticle(wmNews, (short) 8);
            }else{
                saveAppArticle(wmNews, (short) 9);
            }
            //updateWmNews(wmNews,(short)4,"人工审核通过");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
